// pages/select/select.js
import http from "../../utils/http"

Page({
  data: {
    courseList: []
  },
  
  // 获取课程列表
  getSelectList() {
    http({
      url: "/student/course/list",
    }).then(res => {
      console.log(res);
      if (res.code === 0) {
        this.setData({
          courseList: res.data
        })
      }
    })
  },

  // 退选处理函数
  handleWithdraw(e) {
    const courseId = e.currentTarget.dataset.courseId;
    
    if (!courseId) {
      wx.showToast({ title: '课程ID获取失败', icon: 'none' });
      console.error('未获取到课程ID:', e);
      return;
    }
    
    const that = this;
    wx.showModal({
      title: '确认退选',
      content: '确定要退选该课程吗？',
      success(res) {
        if (res.confirm) {
          that.withdrawCourse(courseId);
        }
      }
    });
  },

  // 调用退选API
  withdrawCourse(courseId) {
    wx.showLoading({ title: '处理中...', mask: true });
    
    console.log('退选课程ID:', courseId);
    
    http({
      url: `/student/course/${courseId}`,
      method: 'DELETE'
    }).then(res => {
      wx.hideLoading();
      console.log('退选响应:', res);
      
      if (res.code === 0) {
        wx.showToast({ 
          title: '退选成功', 
          icon: 'success',
          duration: 1500
        });
        
        // 退选成功后重新获取课程列表
        setTimeout(() => {
          this.getSelectList();
        }, 500);
      } else {
        wx.showToast({ 
          title: res.msg || '退选失败', 
          icon: 'none',
          duration: 3000
        });
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({ 
        title: '请求失败，请重试', 
        icon: 'none',
        duration: 3000
      });
      console.error('退选请求失败:', err);
    });
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
   
  },
  
  onShow() {
    this.getSelectList()
  }


  // ...其他生命周期函数保持不变
})